#include "securehttpclient.h"
#include <QJsonObject>
#include <QJsonParseError>

SecureHttpClient::SecureHttpClient(QObject *parent) : QObject(parent) {
    manager = new QNetworkAccessManager(this);
}

void SecureHttpClient::configureSsl(QNetworkRequest &request) {
    QSslConfiguration sslConfig = QSslConfiguration::defaultConfiguration();
    sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone); // 关闭证书验证[1,4](@ref)
    sslConfig.setProtocol(QSsl::TlsV1_2OrLater);         // 强制TLS 1.2+
    request.setSslConfiguration(sslConfig);
}

void SecureHttpClient::get(const QString &url) {
    QNetworkRequest request(url);
    configureSsl(request);

    QNetworkReply *reply = manager->get(request);
    connect(reply, &QNetworkReply::sslErrors, this, &SecureHttpClient::handleSslErrors);
    connect(reply, &QNetworkReply::finished, this, [=](){
        if(reply->error() == QNetworkReply::NoError) {
            handleResponseReady(reply->readAll());
        } else {
            emit requestFailed(-1, reply->errorString());
        }
        reply->deleteLater();
    });
}

void SecureHttpClient::post(const QString &url, QString token, const QByteArray &data) {
    // QString strVersion = "QSslSocket=" + QSslSocket::sslLibraryBuildVersionString();
    // bool bExist = (QSslSocket::supportsSsl() == true ? "true" : "false");
    // qDebug() << strVersion << bExist;

    QNetworkRequest request(url);
    configureSsl(request);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    if (!token.isEmpty()) {
        request.setRawHeader("Authorization", token.toUtf8());
    }

    QNetworkReply *reply = manager->post(request, data);
    connect(reply, &QNetworkReply::sslErrors, this, &SecureHttpClient::handleSslErrors);
    connect(reply, &QNetworkReply::finished, this, [=](){
        if(reply->error() == QNetworkReply::NoError) {
            handleResponseReady(reply->readAll());
        } else {
            qDebug() << "SecureHttpClient: " << reply->errorString();
            emit requestFailed(-1, reply->errorString());
        }
        reply->deleteLater();
    });
}

void SecureHttpClient::handleSslErrors(const QList<QSslError> &errors) {
    // reply->ignoreSslErrors(); // 主动忽略所有SSL错误[1](@ref)
    qWarning() << "Ignored SSL errors:" << errors;
}

void SecureHttpClient::handleResponseReady(const QByteArray &data){
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(data, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        emit requestFailed(-1, "JSON 解析错误：" + parseError.errorString());
        return;
    }

    if (!doc.isObject()){
        emit requestFailed(-1, "登录数据返回格式错误：" + QString(data));
        return;
    }

    QJsonObject obj = doc.object();
    int code = obj["code"].toInt();
    if (code != 200) {
        QString msg = obj["msg"].toString();
        emit requestFailed(code, msg);
        return;
    }

    QJsonObject res = obj["data"].toObject();
    // qDebug() << "data:" << res;
    emit responseReady(res);
}
